#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <time.h>
#include <errno.h>
#include <math.h>
#include <signal.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <semaphore.h>
#include <pthread.h>

#include "dbfunc.h"

#define THREAD_QT               5

typedef struct
{
    pthread_t thrd_id;
} thrd_ctl_t;
static thrd_ctl_t a_thrd_ctl[THREAD_QT+10];

void ThrdFunc(int thrd_index);


int main()
{
    int thrd_index;

    if(DbsInit()!=DB_OK)
    {
        printf("Db init fail\n");
        exit(1);
    }
    for(thrd_index=0; thrd_index<THREAD_QT; thrd_index++)
    {
        if(pthread_create(&a_thrd_ctl[thrd_index].thrd_id, NULL,
               (void *(*)(void *))ThrdFunc, (void *)thrd_index))
        {
            printf("Thread create fail\n");
            exit(1);
        }
    }
    for(thrd_index=0; thrd_index<THREAD_QT; thrd_index++)
    {
        pthread_join(a_thrd_ctl[thrd_index].thrd_id, NULL);
    }

    exit(0);
}


void ThrdFunc(int thrd_index)
{
    int errcode, i;
    char sql[1024];
    emp_t emp;

    if(DbsConnect(thrd_index))
    {
        printf("Thread %d connect fail\n", thrd_index);
        goto ERROR;
    }
    printf("Thread %d Connect OK\n", thrd_index);

    emp.no=thrd_index;
    strcpy(sql, "select no,upd_ts,name,duty,age,salary from emp where no=:no");
    if((errcode=DbsEMP_SEL(thrd_index, sql, &emp))!=DB_OK)
    {
        printf("Thread %d select emp fail, errcode:%d\n",
            thrd_index, errcode);
    }
    else
    {
        printf("no:%.0lf ", emp.no);
        printf("upd_ts:%s ", emp.upd_ts);
        printf("name:%s ", emp.name);
        printf("duty:%s ", emp.duty);
        printf("age:%d ", emp.age);
        printf("salary:%.2lf\n", emp.salary);
        printf("Thread %d select emp succeed\n", thrd_index);
    }

  ERROR:
    DbsDisConnect(thrd_index); 
    return;
} 
